/*
 * Copyright 2020 Mike Penz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mikepenz.iconics.animation;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Rect;

import com.mikepenz.iconics.IconicsBrush;

/**
 * @author pa.gulko zTrap (30.11.2018)
 */
public class SpinProcessor extends IconicsAnimationProcessor {
    private static final long DEFAULT_DURATION = 2000L;
    private final Direction direction = Direction.CLOCKWISE;
    private boolean isDrawableShadowCleared = false;

    /**
     * 默认构造
     */
    public SpinProcessor() {
        setDuration(DEFAULT_DURATION);
        setAnimationTag("spin");
        setRepeatMode(ValueAnimator.RepeatMode.RESTART);
    }

    @Override
    public void processorPreDraw(Canvas canvas, IconicsBrush<Paint> iconBrush, IconicsBrush<Paint> iconContourBrush,
        IconicsBrush<Paint> backgroundBrush, IconicsBrush<Paint> backgroundContourBrush) {
        // Shadow are not recalculate while drawable are spinning. It looks ugly!
        // Turn off ugly shadow!
        if (!isDrawableShadowCleared) {
            iconBrush.getPaint().clearBlurDrawLooper();
            isDrawableShadowCleared = true;
        }
        canvas.save();
        Rect bounds = getDrawableBounds();
        float degrees = getAnimatedPercent() * 3.6f * direction.sign;
        if (bounds != null) {
            canvas.rotate(degrees, bounds.getWidth() / 2f, bounds.getHeight() / 2f);
        }
    }

    @Override
    public void processPostDraw(Canvas canvas) {
        canvas.restore();
    }

    @Override
    protected void onDrawableDetached() {
        isDrawableShadowCleared = false;
    }

    /**
     * 方向
     *
     * @since 2021-06-04
     */
    private enum Direction {
        CLOCKWISE(1), COUNTER_CLOCKWISE(-1);

        private final int sign;

        Direction(int sign) {
            this.sign = sign;
        }
    }
}
